package com.three.filter;

import com.alibaba.fastjson.JSONObject;
import com.three.pojo.Result;
import com.three.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    private static ThreadLocal<Claims> threadLocal = new ThreadLocal<>();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // 获取请求url
        String url = req.getRequestURL().toString();
        log.info("请求的url: {}", url);

        // 判断请求url中是否包含login, 如果包含, 说明是登录操作, 放行。
        if (url.contains("login") || url.contains("register") || url.contains("chat") || url.contains("gpt3")) {
            log.info("登录或注册操作, 放行...");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (req.getMethod().equals("OPTIONS")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 获取请求头中的令牌(token)
        String jwt = req.getHeader("token");

        // 判断令牌是否存在
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头token为空, 返回未登录的信息");
            Result error = Result.fail("NOT_LOGIN");
            // 手动转换(对象转json)
            String notLogin = JSONObject.toJSONString(error);
            // 设置跨域响应头
            resp.setHeader("Access-Control-Allow-Origin", "*"); // 允许的的跨域请求
            resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); // 允许的请求方法
            resp.setHeader("Access-Control-Allow-Headers", "Content-Type, token"); // 允许的请求头
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为401 Unauthorized
            resp.setHeader("Content-Type", "application/json"); // 设置响应类型为 JSON
            resp.getWriter().write(notLogin);
            return;
        }

        Claims jwtClaims;
        // 解析token
        try {
            jwtClaims = JwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败, 返回未登录错误信息");
            Result error = Result.fail("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            // 设置跨域响应头
            resp.setHeader("Access-Control-Allow-Origin", "*"); // 允许的的跨域请求
            resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); // 允许的请求方法
            resp.setHeader("Access-Control-Allow-Headers", "Content-Type, token"); // 允许的请求头
            // 设置其他响应头
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为401 Unauthorized
            resp.setHeader("Content-Type", "application/json"); // 设置响应类型为 JSON
            resp.getWriter().write(notLogin);
            return;
        }

        // 到这里代表token是存在且合法的, 把解析后的token存到threadLocal。
        threadLocal.set(jwtClaims);

        // 放行
        log.info("令牌合法, 放行");
        filterChain.doFilter(servletRequest, servletResponse);

        // 清空 ThreadLocal 对象
        threadLocal.remove();
    }

    public static Claims getCurrentToken() {
        return threadLocal.get();
    }

}